/**
 * 公共辅助性函数
 */
// @ts-ignore
import { format } from "date-fns";
// @ts-ignore
import { ElMessage, ElMessageBox, ElMessageBoxOptions } from "element-plus";
// @ts-ignore
import { getBasicDictList } from "../services/common";

interface GetDictFieldsOpts {
  includes?: string[];
  fieldNames?: string[];
  excludes?: { [key: string]: unknown }[];
}

// 格式化日期辅助函数
export function formatDate(date: string, {
  pattern = "yyyy-MM-dd HH:mm:ss",
  def = "--"
} = {}) {
  if (date) {
    try {
      return date && format(new Date(date), pattern);
    } catch {}
  }
  return def;
}

// 格式化日期辅助函数
export function formatDateNoTime(date: string, {
  pattern = "yyyy-MM-dd",
  def = "--"
} = {}) {
  return formatDate(date, { pattern, def });
}

/**
 * 信息提示辅助工具集
 * @param title
 * @param message
 * @param confirmBtnText
 * @param cancelBtnText
 * @param icon
 * @param type
 * @param {string} to
 * @param showCancelHint
 * @param cancelText
 * @return {boolean}
 */
export async function confirmHint(
  {
    icon,
    message,
    title = "警告",
    confirmBtnText = "确定",
    cancelBtnText = "取消",
    type = "warning",
    to = "body",
    showCancelHint = false,
    cancelText = "成功取消修改~"
  }: ElMessageBoxOptions & {
    confirmBtnText?: string;
    cancelBtnText?: string;
    to?: string;
    showCancelHint?: boolean;
    cancelText?: string;
  }): Promise<boolean> {
  try {
    await (ElMessageBox.confirm(
      message, title,
      {
        type, icon,
        confirmButtonText: confirmBtnText,
        cancelButtonText: cancelBtnText,
        appendTo: to
      }) as Promise<void>);
  } catch {
    showCancelHint && ElMessage.info({
      message: cancelText
    });
    return false;
  }
  return true;
}

/**
 * 获取基础支撑字典字段辅助函数
 * @param {string | number} id 字典项id
 * @param {string[] | undefined} includes 字典返回需要包含的字段
 * @param {string[] | undefined} fieldNames 字典返回包含的字段的自定义别名，与includes对应
 * @return {Promise<{[p: string]: unknown}[]>}
 */
export async function getBasicDictFields(
  id: string | number,
  {
    includes = ["code", "name"],
    fieldNames = ["code", "name"]
  }: GetDictFieldsOpts = {}
): Promise<{ [f: string]: unknown }[]> {
  const { code, data } = await getBasicDictList({ groupCode: id });
  if (code && code === 200) {
    return data.map((item: Record<string, unknown>) => {
      const dict: Record<string, unknown> = {};
      for (const index in includes) {
        const k = fieldNames[index],
          v = includes[index];
        dict[k] = item?.[v];
      }
      return dict;
    });
  }
  return [];
}

// 格式化小数点后几位，（num为字符串或者数值型）
export function formatNumber(num: number | string, decimalPlace: number = 2 ) {
  if (!num) {
    return 0
  }
  try {
    let hasDecimal;
    // 判断是否包含小数点
    if (typeof num === 'number') {
      hasDecimal =  String(num).includes('.') ;
    } else if (typeof num === 'string') {
      hasDecimal =  num.includes('.') ;
    }
    if (hasDecimal) {
      return Number(num).toFixed(decimalPlace)
    } else {
      return num
    }
  } catch (err) {
    return 0
  }
}
